package com.base.saas.gateway.trace;

import org.slf4j.MDC;

import java.util.UUID;

/**
 * @author 王清亮
 * @date 2025/8/2 22:19
 * @description TODO
 */
public class TraceContext {
    public static final String TRACE_ID = "traceId";
    public static final String SPAN_ID = "spanId";
    public static final String PARENT_SPAN_ID = "parentSpanId";

    // 初始化跟踪上下文
    public static void initTrace() {
        if (MDC.get(TRACE_ID) == null) {
            String traceId = UUID.randomUUID().toString().replace("-", "");
            MDC.put(TRACE_ID, traceId);
            // 根span设置为0
            MDC.put(SPAN_ID, "0");
        }
    }

    // 生成新的Span ID
    public static String generateSpanId() {
        return UUID.randomUUID().toString().substring(0, 8);
    }

    // 获取当前Trace ID
    public static String getTraceId() {
        return MDC.get(TRACE_ID);
    }

    // 获取当前Span ID
    public static String getSpanId() {
        return MDC.get(SPAN_ID);
    }

    // 清除上下文
    public static void clear() {
        MDC.clear();
    }
}
